package com.kayoxu.ble_printer.utils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class PrintUtils {

//    public static void printLeft(PrinterInstance mPrinter, String data) {
//        mPrinter.init();
//        mPrinter.printText(data);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 0);
//    }
//
//    public static void printLeftBig(PrinterInstance mPrinter, String data) {
//        mPrinter.init();
//        mPrinter.setFont(0, 0, 0, 0);
//        mPrinter.setPrintModel(true, true, false, false);
//        mPrinter.printText(data);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 0);
//    }
//
//    public static void printLeftVeryBig(PrinterInstance mPrinter, String data) {
//        mPrinter.init();
//        mPrinter.setFont(0, 0, 0, 0);
//        mPrinter.setPrintModel(true, true, true, false);
//        mPrinter.printText(data);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 0);
//    } 
//
//    public static void printLeftRight(PrinterInstance mPrinter, String left, String right) {
//        mPrinter.init();
//        String data = leftRight(left, right);
//        mPrinter.printText(data);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 0);
//    }
//
//    public static void printLeftRightBig(PrinterInstance mPrinter, String left, String right) {
//        mPrinter.init();
//        mPrinter.setFont(0, 0, 0, 0);
//        String data = leftRight(left, right);
//        mPrinter.setPrintModel(true, true, false, false);
//        mPrinter.printText(data);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 0);
//    }
//
//    public static void printLine(PrinterInstance mPrinter) {
//        mPrinter.init();
//        String data = "--------------------------------";
//        mPrinter.printText(data);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 0);
//    }
//
//    public static void printEmptyLine(PrinterInstance mPrinter, int lines) {
//        mPrinter.init();
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, lines);
//    }
//
//
//    public static void printQrCode(PrinterInstance mPrinter, String data, int height) {
//        mPrinter.init();
//        Bitmap bitmap = generateBitmap(data, height, height);
//        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);
//        mPrinter.printImage(bitmap);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 1);
//    }
//
//    public static void printBarcode(PrinterInstance mPrinter, String data, int width, int height, boolean showCode) {
//        mPrinter.init();
//        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);
//        Barcode barcode4 = new Barcode(PrinterConstants.BarcodeType.CODE128, width, height, showCode ? 2 : 0, data);
//        mPrinter.printBarCode(barcode4);
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, showCode ? 1 : 0);
//
//    }
//
//
//    public static void printBitmap(PrinterInstance mPrinter, Bitmap bitmap) {
//        mPrinter.init();
//        mPrinter.printImage(bitmap, 384, 0);
//    }
//
//
//    public static void printImage(Resources resources, PrinterInstance mPrinter) {
//        mPrinter.init();
//        mPrinter.setFont(0, 0, 0, 0);
//        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_LEFT);
//        mPrinter.printText("WWWQ");
//        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2);
//
//        Bitmap bitmap1 = null;
//        try {
//            bitmap1 = BitmapFactory.decodeStream(resources.getAssets().open("android.png"));
//        } catch (IOException e) {
//            e.printStackTrace();
//            return;
//        }
//        mPrinter.printImage(bitmap1);
//        mPrinter.printText("\n\n\n\n");                     //换4行
//
//        try {
//            bitmap1 = BitmapFactory.decodeStream(resources.getAssets().open("support.png"));
//        } catch (IOException e) {
//            e.printStackTrace();
//            return;
//        }
//        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);   //设置打印居中
//        mPrinter.printText("11");
//        mPrinter.printImage(bitmap1);
//        mPrinter.printText("\n\n\n\n");                     //换4行
//    }
//
//
//    public static void printBigData(Resources resources, PrinterInstance mPrinter) {
//        try {
//            InputStream is = resources.getAssets().open("58-big-data-test.bin");
//            int length = is.available();
//            byte[] fileByte = new byte[length];
//            is.read(fileByte);
//            mPrinter.init();
//            mPrinter.sendByteData(fileByte);
//            is.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//
//    public static void printUpdate(Resources resources, PrinterInstance mPrinter, String filePath) {
//        try {
//
//            FileInputStream fis = new FileInputStream(new File(filePath));
//            //InputStream is = resources.getAssets().open("PT8761-HT-BAT-9170.bin");
//            int length = fis.available();
//            byte[] fileByte = new byte[length];
//            fis.read(fileByte);
//            mPrinter.init();
//            mPrinter.updatePrint(fileByte);
//            fis.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    public static Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter writer = new QRCodeWriter();
        Map<EncodeHintType, String> hint = new HashMap<>();
        hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hint);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String leftRight(String left, String right, boolean doubleWidth) {
        String printText = "";
        String takeUp = " ";                // 填充字符
        String nameStr = left;
        int leftLen = byteNum(nameStr) * (doubleWidth ? 2 : 1);
        int rightLen = byteNum(right) * (doubleWidth ? 2 : 1);

        if (leftLen + rightLen < 33) {
            printText += nameStr;
            for (int i = 0; i < (32 - leftLen - rightLen) / (doubleWidth ? 2 : 1); i++) {
                printText += takeUp;
            }
            printText += right;
            return printText;
        } else {
            return left + takeUp + right;
        }
    }

    /**
     * 58mm打印机 商品打印样式
     * 样式：################# ++++ ---- ****(title--msg)
     *
     * @param left
     * @param right
     */
    @Deprecated
    public static String leftRight(String left, String right) {
        String printText = "";
        String takeUp = " ";                // 填充字符
        String nameStr = left;
        int leftLen = byteNum(nameStr);
        int rightLen = byteNum(right);
        if (leftLen < 17) {
            printText += nameStr;
            for (int i = 0; i < 17 - leftLen; i++)
                printText += takeUp;
            leftLen -= byteNum(nameStr);
        } else {
            printText += nameStr.substring(0, 8);
            printText += takeUp;
            leftLen -= byteNum(nameStr.substring(0, 8));
            nameStr = nameStr.substring(8, nameStr.length());
        }

        if (rightLen < 14) {
            for (int i = 0; i < 14 - rightLen; i++)
                printText += takeUp;
            printText += right;
        } else {
            return "-2";
        }

        printText += "\n";
        while (leftLen > 0) {
            if (leftLen > 16) {
                printText += nameStr.substring(0, 8);
                leftLen -= byteNum(nameStr.substring(0, 8));
                nameStr = nameStr.substring(8, nameStr.length());
            } else {
                printText += nameStr;
                leftLen -= byteNum(nameStr);
            }
            printText += "\n";
        }
        return printText;
    }

    /**
     * 58mm打印机 商品打印样式
     * 样式：################# ++++ ---- ****(#名称 +单价 -数量 *总计)
     *
     * @param name   商品名称
     * @param price  商品单价 不能大于99.9元
     * @param number 商品数量 不能大于9999个
     * @param total  商品总计 不能大于99.9元
     * @return 返回商品打印样式。
     * -1 ：名称格式错误
     * -2 ：单价格式错误
     * -3 ：数量格式错误
     * -4 ：总计格式错误
     */
    public static String commodity58Print(String name, String price, String number, String total) {
        String printText = "";
        String takeUp = " ";                // 填充字符
        String nameStr = name;
        int nameLen = byteNum(nameStr);
        int priceLen = byteNum(price);
        int numberLen = byteNum(number);
        int totalLen = byteNum(total);
        if (nameLen < 17) {
            printText += nameStr;
            for (int i = 0; i < 17 - nameLen; i++)
                printText += takeUp;
            nameLen -= byteNum(nameStr);
        } else {
            printText += nameStr.substring(0, 8);
            printText += takeUp;
            nameLen -= byteNum(nameStr.substring(0, 8));
            nameStr = nameStr.substring(8, nameStr.length());
        }

        if (priceLen < 5) {
            for (int i = 0; i < 5 - priceLen; i++)
                printText += takeUp;
            printText += price;
        } else {
            return "-2";
        }

        if (numberLen < 5) {
            for (int i = 0; i < 5 - numberLen; i++)
                printText += takeUp;
            printText += number;
        } else {
            return "-3";
        }

        if (totalLen < 5) {
            for (int i = 0; i < 5 - totalLen; i++)
                printText += takeUp;
            printText += total;
        } else {
            return "-4";
        }
        printText += "\n";
        while (nameLen > 0) {
            if (nameLen > 16) {
                printText += nameStr.substring(0, 8);
                nameLen -= byteNum(nameStr.substring(0, 8));
                nameStr = nameStr.substring(8, nameStr.length());
            } else {
                printText += nameStr;
                nameLen -= byteNum(nameStr);
            }
            printText += "\n";
        }
        return printText;
    }

    /**
     * 获取占用打印位：汉字二个打印位、英文数字符号一个打印位
     *
     * @param str
     * @return
     */
    public static int byteNum(String str) {
        int m = 0;
        char arr[] = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            char c = arr[i];
            if ((c >= 0x0391 && c <= 0xFFE5))  //中文字符
                m = m + 2;
            else if ((c >= 0x0000 && c <= 0x00FF)) //英文字符
                m = m + 1;
        }
        return m;
    }

    public static Bitmap view2Bitmap(View view, int height) {
//        if (view == null) {
//            return null;
//        }
//        int intw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
//        int inth = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
//        view.measure(intw, inth);
//        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
//        Canvas canvas = new Canvas(bitmap);
//        canvas.drawColor(Color.WHITE);
//        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
//        view.draw(canvas);
//        return bitmap;


        if (view == null) {
            return null;
        } else {
//            BitmapDescriptor var1 = null;

            try {
                view.measure(384, height);
                view.layout(0, 0, 384, height);
                view.buildDrawingCache();
                Bitmap var2 = view.getDrawingCache();
//                var1 = fromBitmap(var2);
//                if (var2 != null) {
//                    var2.recycle();
//                }
                return var2;
//                view.destroyDrawingCache();
//                return var1;
            } catch (Exception var3) {
                return null;
            }
        }


//        view.clearFocus();
//        view.setPressed(false);
//        boolean willNotCache = view.willNotCacheDrawing();
//        view.setWillNotCacheDrawing(false);
//        int color = view.getDrawingCacheBackgroundColor();
//        view.setDrawingCacheBackgroundColor(0);
//        if (color != 0) {
//            view.destroyDrawingCache();
//        }
//        view.buildDrawingCache();
//        Bitmap cacheBitmap = view.getDrawingCache();
//        if (cacheBitmap == null) {
//            return null;
//        }
//        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
//        view.destroyDrawingCache();
//        view.setWillNotCacheDrawing(willNotCache);
//        view.setDrawingCacheBackgroundColor(color);
//        return bitmap;


    }

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public static String getConnectedBtDevice() {
        //获取蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //得到已匹配的蓝牙设备列表
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices != null && bondedDevices.size() > 0) {
            for (BluetoothDevice bondedDevice : bondedDevices) {
                try {
                    //使用反射调用被隐藏的方法
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    isConnectedMethod.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(bondedDevice, (Object[]) null);
                    Log.e("123", "isConnected：" + isConnected);
                    if (isConnected) {
                        return bondedDevice.getAddress();
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
